package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExceListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-11-16
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        //添加课程分类
        try{
            InputStream in = file.getInputStream();

            EasyExcel.read(in, SubjectData.class,new SubjectExceListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //课程分类树形结构
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询所有一级分类  parenid = 0
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id",0);
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapperOne);
        //查询所有的二级分类  parenid !=0
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperOne.ne("parent_id",0);
        List<EduSubject> twoSubjects = baseMapper.selectList(wrapperTwo);

        List<OneSubject> finallSubject = new ArrayList<>();
        //封装一级分类

        for (int i = 0; i < oneSubjects.size(); i++) {
            EduSubject eduSubject = oneSubjects.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finallSubject.add(oneSubject);

            List<TwoSubject> twoFinallList = new ArrayList<>();
            for (int j = 0; j < twoSubjects.size(); j++) {
                EduSubject tsubject = twoSubjects.get(j);
                //判断二级分类的parentid是否和一级分类的id一样
                if(tsubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tsubject,twoSubject);
                    twoFinallList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoFinallList);
        }
        //封装二级分类

        return finallSubject;
    }
}
